from tools import *
import urllib
import urllib2
import random
import subprocess

LOG = getlogger(__name__)


def get_old():
    addr = os.path.join(BASEURL, 'info/oldpass')
    param = urllib.urlencode(dict({'signature': UUID}))
    f = urllib2.urlopen(addr, param)
    code = f.getcode()
    result = f.read()
    if code == 200:
        return result
    else:
        raise Exception('HTTP COEE:%d' % code)


codes = [range(33, 47), range(48, 58), range(58, 65), range(65, 123)]


def change(old, new):
    proc = subprocess.Popen(['/usr/bin/passwd'],
                            stdin=subprocess.PIPE,
                            stdout=subprocess.PIPE,
                            stderr=subprocess.PIPE)
    proc.stdin.write(old + '\n')
    proc.stdin.write(new + '\n')
    proc.stdin.write(new + '\n')
    proc.stdin.flush()
    ret, err = proc.communicate()
    if 'successfully' in ret:  #all authentication tokens updated successfully
        return True
    else:
        print False


def submit(new):
    addr = os.path.join(BASEURL, 'info/passwd')
    param = urllib.urlencode(dict({'signature': UUID, 'altered': new}))
    f = urllib2.urlopen(addr, param)
    code = f.getcode()
    result = f.read()
    if code == 200:
        return result
    else:
        raise Exception('HTTP COEE:%d' % code)


def generate_new():
    new = ''
    for i in range(0, 12):
        new += bytes(chr(random.choice(random.choice(codes))))
    return new


def main():
    LOG.info('generate new pass')
    new = generate_new()
    old = get_old()
    ret = change(old, new)
    LOG.info('change new pass ' + str(ret))
    submit(new)
    LOG.info('submit new pass ')
    return 'OK'
